package main

import (
	"fmt"
	"net"
	"sort"
	"sync"
	"time"
)

// scanPort checks if a port is open on the given host.
func scanPort(protocol, hostname string, port int, wg *sync.WaitGroup) []int {
	defer wg.Done()
	address := fmt.Sprintf("%s:%d", hostname, port)
	conn, err := net.DialTimeout(protocol, address, 1*time.Second)
	if err != nil {
		return nil
	}
	conn.Close()
	return []int{port}
}

func main() {
	hostname := "127.0.0.1"
	// hostname := "scanme.nmap.org"
	protocol := "tcp"
	var openPorts []int
	var wg sync.WaitGroup
	const maxPort = 1024 // You can adjust the range based on your needs

	for port := 1; port <= maxPort; port++ {
		wg.Add(1)
		go func(port int) {
			if result := scanPort(protocol, hostname, port, &wg); result != nil {
				openPorts = append(openPorts, result...)
			}
		}(port)
	}
	wg.Wait()

	sort.Ints(openPorts) // Sort the slice of open ports
	fmt.Printf("Open ports: %v\n", openPorts)
}
